<template>
  <div class="tab-container">
    <!--  head  -->
    <div class="filter-container">
      <el-affix :offset="120">
        <el-button type="primary" :icon="Edit" plain @click="handlerAdd">新增</el-button>
        <!--      <el-button type="primary" :icon="Check" plain>保存</el-button>-->
        <el-button type="danger" :icon="Delete" plain @click="selectDelete">删除</el-button>
        <el-button v-if="tableState" type="success" plain @click="backtrack">返回</el-button>
      </el-affix>
    </div>

    <!--  content   -->
    <div v-if="!tableState">
      <el-table column-key="tag"
                ref="multipleTable"
                :data="resultData.tableData?.filter(data => !searchVal || data.labelName.toLowerCase().includes(searchVal.toLowerCase()))"
                style="width: 100%;cursor: pointer;"
                @selection-change="selectionChange" @row-click="handlerSelectType">
        <el-table-column type="selection" width="60"/>
        <el-table-column
            align="center"
            label="类别名称"
            prop="labelName">
          <template #default="scope">
            <el-popover effect="'light'" trigger="hover" placement="top" width="170">
              <template #default>
                <div>名称: {{ scope.row.labelName }}</div>
                <div>创建时间: {{ scope.row.createDate }}</div>
              </template>
              <template #reference>
                <span>{{ scope.row.labelName }}</span>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column
            align="center"
            label="描述"
            prop="content">
          <template #default="scope">
            <el-popover effect="'dark'" placement="top-start" :width="100" trigger="hover" :content="scope.row.content">
              <template #reference> {{ scope.row.content?.slice(0, 6) }}...</template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column
            align="center"
            label="Tag"
            prop="tag"
            column-key="tag"
            sortable
            :filters="tag"
            :filter-method="filterTag"
            filter-placement="bottom-end">
          <template #default="scope">
            <i class="status"
               :style="{backgroundColor: scope.row.state===0?'springgreen':(scope.row.state===1?'red':'#e88055')}"/>
            <span style="display: inline-block;"> {{ scope.row.tag }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right">
          <template #header>
            <el-input v-model="searchVal" icon="Search" size="small" placeholder="输入关键字搜索" clearable/>
          </template>
          <template #default="scope">
            <el-button type="primary" plain size="small" @click.stop="handleSelectEdit(scope.$index,scope.row)">编辑
            </el-button>
            <el-button type="danger" plain size="small" @click.stop="handleSelectDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div>
        <!--   增加弹框,编辑弹框   -->
        <el-dialog v-if="editState"
                   v-model="editState"
                   :title="addState?'新增':'编辑'"
                   width="30%"
                   align-center
                   draggable>
          <el-form :model="resultData.selectRowVal" :label-position="'top'">
            <el-form-item label="类别名称:">
              <el-input v-model="resultData.selectRowVal.labelName" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="描述:">
              <el-input type="textarea" v-model="resultData.selectRowVal.content" autocomplete="off"/>
            </el-form-item>
          </el-form>

          <template #footer>
          <span class="dialog-footer">
            <el-button @click="editState = false">Cancel</el-button>
            <el-button type="primary" @click="handleEdit">Save</el-button>
          </span>
          </template>
        </el-dialog>
      </div>
    </div>

    <!--  功能页   -->
    <div v-else-if="tableState">
      <!--  子组件绑定需要的父组件数据    -->
      <ToolFeat v-model:feat-add-state="featAddState" v-model:id="resultData.selectRowVal.id"
                v-model:table-state="tableState" v-model:select-row-val="resultData.selectRowVal"
                v-model:feat-list="resultData.selectRowVal.featList"/>
    </div>
  </div>

</template>

<script lang="ts">
import axios from "axios";
import {useRouter} from "vue-router";

export default {
  name: "Index",
  components: {useRouter},
  data() {
    return {
      tag: [
        {text: '在线', value: 'online'},
        {text: '离线', value: 'offline'}
      ],
    }
  },
  created() {
  },
  methods: {},
}
</script>

<script setup lang="ts">
import {Delete, Edit, Search, Share, Upload, Check, Timer} from '@element-plus/icons-vue'
import {onMounted, onUnmounted, reactive, ref} from "vue";
import ToolFeat from './tool-feature/TooFeature.vue'
import {ElMessage, ElMessageBox, ElTable} from "element-plus";

// 属性
/**
 * 类别
 */
interface Classify {
  id: number,
  labelName: string,
  content: string,
  createDate: string,
  tag: string,
  state: number
}

const resultData = reactive({
  // 列表数据
  tableData: [],
  // 选择行数据
  selectRowVal: {},
  // 选择的数据
  selectVal: [],
})

// 选择的索引
let selectIndex: number;

// 搜索
let searchVal = ref("");
// 新增状态
const addState = ref(false)
// 编辑状态
const editState = ref(false)
// 列表显示状态, false: 显示列表, ture: 显示类别下的功能列表
const tableState = ref(false)

// 功能页功能按钮, false: 类别页, true: 功能页
const featAddState = ref(false)

const multipleTable = ref<InstanceType<typeof ElTable>>();

// -----------------------函数, todo 编辑保存, 删除进行弹框提示, 并走实际的接口

/**
 * 返回触发
 */
const backtrack = () => {
  tableState.value = false
  convertData(resultData.tableData)
}

/**
 * 选择类别
 */
const handlerSelectType = (row) => {
  // 展示对应类别下的内容
  // selectRowVal.val = row;
  resultData.selectRowVal = row;
  tableState.value = true;
}

/**
 * 复选框选择行
 * @param val 行数据
 */
const selectionChange = (val) => {
  resultData.selectVal = val;
  // console.log("选择: " + JSON.stringify(val))
}

/**
 * 过滤tag
 * @param val 过滤的数据
 * @param row 列表数据
 */
const filterTag = (val: string, row) => {
  return row.tag === val;
}

/**
 * 新增编辑
 */
const handlerAdd = () => {

  if (!tableState.value) {
    addState.value = true;
    // 清除选择的历史数据
    resultData.selectRowVal = {};
    // 设置默认状态
    resultData.selectRowVal.tag = 'offline'
    // 显示编辑框
    editState.value = true;
  } else {
    // 当前显示功能页时, 为功能页服务
    featAddState.value = true;
  }
}

/**
 * 处理编辑的行, 弹框编辑数据
 * @param index 行号
 * @param row 行数据
 */
const handleSelectEdit = (index: number, row) => {
  // 回显值
  resultData.selectRowVal = JSON.parse(JSON.stringify(row));
  selectIndex = index;

  // 显示编辑框
  editState.value = true;
}

/**
 * 处理编辑-弹框保存
 * @param index 行索引
 * @param row
 */
const handleEdit = () => {
  if (addState.value) {
    // 新增-在列表中添加新数据
    resultData.tableData.push(resultData.selectRowVal);
    addState.value = false;
  } else {
    // 修改对应的行数据
    resultData.tableData.splice(selectIndex, 1, resultData.selectRowVal);
  }
  resultData.selectRowVal = {};
  // 隐藏编辑框
  editState.value = false;
}

/**
 * 处理删除行-单元行删除
 * @param index 行号
 */
const handleSelectDelete = (index: number) => {
  handleMessage(index);
}

/**
 * 删除选择的数据-顶部删除
 */
const selectDelete = () => {
  let ids = resultData.selectVal.map(item => item.id);
  // console.log("选择: " + JSON.stringify(resultData.selectVal))
  handleMessage(ids);
}

const handleMessage = (ids) => {
  ElMessageBox.confirm('确认删除选择的选项吗!', '警告', {
    type: 'warning',
  }).then(() => {
    let msg = '';
    let indexList = Array.isArray(ids) ? Array.from(ids) : Array.of(ids);
    if (indexList.length != 0) {
      // todo 走接口处理
      // console.log("ids : " + JSON.stringify(indexList))
      resultData.tableData = resultData.tableData
          .filter(item => !indexList.includes(item.id))
      resultData.selectVal.length = 0;
      // console.log("选择数据: " + JSON.stringify(resultData.selectVal));
      msg = '删除成功'
    } else {
      msg = '未选择任何数据'
    }
    ElMessage({
      type: 'success',
      message: msg
    })
  }).catch(() => {
    resultData.selectVal.length = 0;
    // 清除表格选中状态
    multipleTable.value!.clearSelection();
    ElMessage({
      type: 'info',
      message: 'Delete canceled',
    })
  })
}


// todo mock 测试数据
onMounted(() => getData())

// 清理定时器
onUnmounted(() => {
  clearInterval(timer.value)
  timer.value = '';
})

let isData = ref(false)
let timer = ref()
const getData = () => {
  timer.value = setInterval(() => {
    if (!isData.value) {
      getList();
    } else {
      // 关闭定时器
      clearInterval(timer.value)
    }
  }, 100)
}
const getList = () => {
  axios.get('/data/test')
      .then(res => {
        let list = res.data.list;
        // console.log("setup 请求: " + JSON.stringify(list));
        // 替换tag
        if (list) {
          isData.value = true;
          // list.map(item => {
          //   let result = 0;
          //   item.featList.forEach(val => {
          //     if (val.runState) {
          //       return result++;
          //     }
          //   })
          //   if (result === 0) {
          //     item.tag = "离线"
          //     item.state = 1;
          //   } else if (result === item.featList.length) {
          //     item.tag = "在线"
          //     item.state = 0;
          //   } else {
          //     item.tag = "部分在线"
          //     item.state = 2;
          //   }
          // })
          convertData(list);
          resultData.tableData = list;
        }
      })
}

// 数据数据转换, todo 后续通过接口进行判断类型
const convertData = (dataArray: []) => {
  dataArray.map(item => {
    let result = 0;
    item.featList.forEach(val => {
      if (val.runState) {
        return result++;
      }
    })
    if (result === 0) {
      item.tag = "离线"
      item.state = 1;
    } else if (result === item.featList.length) {
      item.tag = "在线"
      item.state = 0;
    } else {
      item.tag = "部分在线"
      item.state = 2;
    }
  })
}

</script>


<style scoped>
.filter-container {
  height: 60px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

.status {
  //background-color: springgreen;
  width: 8px;
  height: 8px;
  margin-top: 6px;
  margin-right: 8px;
  border-radius: 50%;
  display: inline-block;
}
</style>